package com.example.musicplayer;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.musicplayer.listener.MusicHandlerListener;
import com.example.musicplayer.model.BroadActions;

import java.util.Objects;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, MusicHandlerListener {
    final String TAG = "Broadcast";
    MusiclistFragment musiclistFragment;
    private ObjectAnimator animator;
    Button nextBt, lastBt, listBt, playBt;
    static SeekBar proSB;//歌曲进度条
    TextView singerTv, musicTv;
    private View mMusicICon;
    Boolean isPlaying = true, isBound = false;
    IMusicService iMusicService;
    Integer songOrder = 0;//正在播放的歌曲编号
    BroadcastReceiver musicReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (Objects.requireNonNull(intent.getAction())) {
                case BroadActions.CONTINUE_MUSIC:
                    Log.d(TAG, "onReceive: ====> 接收广播");
                    Toast.makeText(MainActivity.this, "广播：接着奏乐接着舞！", Toast.LENGTH_SHORT).show();
                    break;
                case BroadActions.PAUSE_MUSIC:
                    Toast.makeText(MainActivity.this, "广播：爱妃等朕上厕所！", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            iMusicService = IMusicService.Stub.asInterface(iBinder);
            try {
                iMusicService.RegisterCallback(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
                Log.d(TAG, "onServiceConnected: 出错了");
            }
            isBound = true;
            try {
                startSong(songOrder);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            try {
                iMusicService.unRegisterCallback(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
                Log.d(TAG, "onServiceDisconnected: 出错了");
            }
            iMusicService = null;
            isBound = false;
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        // 获取frag传入的歌曲信息
        getSongInit();
        // 启动服务（保持服务运行）
        Intent startIntent = new Intent(this, MusicService.class);
        startService(startIntent);
        // 绑定服务
        MusicService.setListener(this);
        Intent serIntent = new Intent(this, MusicService.class);
        bindService(serIntent, connection, Context.BIND_AUTO_CREATE);
        // 注册广播接收器
        registerReceiver();
    }

    // 获取frag传入的歌曲信息
    private void getSongInit() {
        Intent intent = getIntent();
        songOrder = intent.getIntExtra("pos", 0);
        String musicName = intent.getStringExtra("musicName");
        String singerName = intent.getStringExtra("singerName");

        singerTv.setText(singerName);
        musicTv.setText(musicName);
    }

    // 注册广播接收器
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void registerReceiver() {
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction(BroadActions.CONTINUE_MUSIC);
        intentFilter1.addAction(BroadActions.PAUSE_MUSIC);
        registerReceiver(musicReceiver, intentFilter1);
    }

    void Init() {
        musiclistFragment = new MusiclistFragment();
        // 获取大的音乐图标
        mMusicICon = findViewById(R.id.music_icon);
        //动画
        //rotation和0f,360.0f就设置了动画是从0°旋转到360°
        animator = ObjectAnimator.ofFloat(mMusicICon, "rotation", 0f, 360.0f);
        animator.setDuration(10000);//动画旋转一周的时间为10秒
        animator.setInterpolator(new LinearInterpolator());//匀速
        animator.setRepeatCount(-1);//-1表示设置动画无限循环

        nextBt = findViewById(R.id.main_next);
        lastBt = findViewById(R.id.main_last);
        listBt = findViewById(R.id.main_menu);
        playBt = findViewById(R.id.main_play);

        nextBt.setOnClickListener(this);
        lastBt.setOnClickListener(this);
        listBt.setOnClickListener(this);
        playBt.setOnClickListener(this);

        musicTv = findViewById(R.id.main_music_name);
        singerTv = findViewById(R.id.main_music_singer);
        // 进度条
        proSB = findViewById(R.id.main_sb);
        proSB.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress == seekBar.getMax()) {
                    animator.pause();
                }
            }

            //滑动条开始滑动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            //滑动条停止滑动
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int prog = seekBar.getProgress();
                try {
                    iMusicService.seekTo(prog);
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        });

    }

    /**
     * button事件指定服务方法
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_play:
                // 暂停/继续：进行UI更新以及服务方法的调用
                if (isPlaying) {
                    try {
                        iMusicService.pausePlay();
                        playBt.setBackgroundResource(R.drawable.pause);
                        animator.pause();
                        isPlaying = false;
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    try {
                        iMusicService.ContinuePlay();
                        animator.start();
                        isPlaying = true;
                        playBt.setBackgroundResource(R.drawable.start);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                break;
            case R.id.main_next:
                // 下一首
                try {
                    songOrder = (songOrder + 1) % 3;
                    startSong(songOrder);
                    singerTv.setText(MusiclistFragment.dataList.get(songOrder).getSingerName());
                    musicTv.setText(MusiclistFragment.dataList.get(songOrder).getMusicName());
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
                break;
            case R.id.main_last:
                // 上一首
                try {
                    songOrder = (songOrder + 3 - 1) % 3;
                    startSong(songOrder);
                    singerTv.setText(MusiclistFragment.dataList.get(songOrder).getSingerName());
                    musicTv.setText(MusiclistFragment.dataList.get(songOrder).getMusicName());
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
                break;
            case R.id.main_menu:
                // 显示歌曲列表的菜单
                showFragment();
            default:
                break;
        }
    }

    /**
     * 开始播放
     */
    private void startSong(int songOrder) throws RemoteException {
        // 其实没有必要传入参数，但是来都来了
        iMusicService.Play(songOrder);
        animator.start();
        isPlaying = true;
        playBt.setBackgroundResource(R.drawable.start);
    }

    //显示菜单fragment
    private void showFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.my_fragment, musiclistFragment);
        transaction.commit();
        findViewById(R.id.my_fragment).bringToFront();
    }

    //获取进度条信息
    public static Handler handler = new Handler() {
        public String TAG = "handler";

        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();

            int duration = bundle.getInt("duration");
            int curPos = bundle.getInt("curPos");
            Log.d(TAG, "handleMessage:===>时长:" + duration + "目前进度:" + curPos);
            proSB.setMax(duration);
            proSB.setProgress(curPos);
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    /**
     * 销毁
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        unregisterReceiver(musicReceiver);
//        iMusicService = null;
        connection = null;
    }

    /**
     * 回调处理传给handler的消息
     *
     * @param what
     * @param data
     */
    @Override
    public void sendMsgToHandler(Integer what, Object data) {
        Message msg = handler.obtainMessage();
        msg.what = what;
        msg.setData((Bundle) data);
        handler.sendMessage(msg);
    }

    private final IMusicServiceCallback callback = new IMusicServiceCallback.Stub() {

        @Override
        public void updateProgress(int duration, int curPos) throws RemoteException {
            Log.d(TAG, "handleMessage:===>时长:" + duration + "目前进度:" + curPos);
            proSB.setMax(duration);
            proSB.setProgress(curPos);
        }
    };
}
